<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>薪酬管理 - 薪酬设置</title>
    <link rel="stylesheet" href="../css/style.css">
    <script src="../js/jquery-1.8.3.js"></script>
    <script src="../js/utils.js"></script>
    <script src="../js/api.js"></script>
    <script type="module" src="../js/components/navigation.js"></script>
</head>
<body>
    <div class="app-container">
        <header class="app-header">
            <div class="logo">员工管理系统</div>
            <div class="user-info">
                <span id="username-display"></span>
                <button id="logout-btn" class="btn btn-secondary">退出登录</button>
            </div>
        </header>

        <div class="app-body">
            <aside class="sidebar">
                <nav class="menu">
                    <ul>
                        <li><a href="#" class="menu-item active" data-target="welcome">欢迎页</a></li>
                        <li class="menu-group">
                            <a href="#" class="menu-item">员工管理</a>
                            <ul class="submenu">
                                <li><a href="../employee/list.html" class="submenu-item">员工列表</a></li>
                                <li><a href="../employee/add.html" class="submenu-item">添加员工</a></li>
                            </ul>
                        </li>
                        <li class="menu-group">
                            <a href="#" class="menu-item">业务管理</a>
                            <ul class="submenu">
                                <li><a href="../business/list.html" class="submenu-item">业务列表</a></li>
                                <li><a href="../business/create.html" class="submenu-item">创建业务</a></li>
                            </ul>
                        </li>
                        <li class="menu-group">
                            <a href="#" class="menu-item">薪酬管理</a>
                            <ul class="submenu">
                                <li><a href="overview.html" class="submenu-item">薪酬概览</a></li>
                                <li><a href="manage.html" class="submenu-item">薪酬管理</a></li>
                            </ul>
                        </li>
                        <li class="menu-group">
                            <a href="#" class="menu-item">系统设置</a>
                            <ul class="submenu">
                                <li><a href="../system/user.html" class="submenu-item">用户管理</a></li>
                                <li><a href="../system/profile.html" class="submenu-item">个人设置</a></li>
                            </ul>
                        </li>
                    </ul>
                </nav>
            </aside>

            <main class="content">
                <div class="form-container">
                    <h2 class="form-title">薪酬管理</h2>
                    <div class="employee-info-card">
                        <div class="card-header">
                            <h3>员工信息</h3>
                        </div>
                        <div class="card-body">
                            <div class="info-row">
                                <div class="info-label">员工姓名:</div>
                                <div class="info-value" id="employee-name"></div>
                            </div>
                            <div class="info-row">
                                <div class="info-label">部门:</div>
                                <div class="info-value" id="employee-department"></div>
                            </div>
                            <div class="info-row">
                                <div class="info-label">职位:</div>
                                <div class="info-value" id="employee-position"></div>
                            </div>
                            <div class="info-row">
                                <div class="info-label">入职日期:</div>
                                <div class="info-value" id="employee-hire-date"></div>
                            </div>
                        </div>
                    </div>

                    <form id="salary-form">
                        <input type="hidden" id="employee-id" name="employeeId">
                        <div class="form-group">
                            <label for="effective-date">生效日期 <span style="color: red;">*</span></label>
                            <input type="date" id="effective-date" name="effectiveDate">
                        </div>
                        <div class="form-group">
                            <label for="base-salary">基本工资 <span style="color: red;">*</span></label>
                            <input type="number" id="base-salary" name="baseSalary" placeholder="请输入基本工资" step="0.01">
                        </div>
                        <div class="form-group">
                            <label for="bonus">奖金</label>
                            <input type="number" id="bonus" name="bonus" placeholder="请输入奖金" step="0.01">
                        </div>
                        <div class="form-group">
                            <label for="benefits">福利</label>
                            <input type="number" id="benefits" name="benefits" placeholder="请输入福利" step="0.01">
                        </div>
                        <div class="form-group">
                            <label for="insurance">社保</label>
                            <input type="number" id="insurance" name="insurance" placeholder="请输入社保" step="0.01">
                        </div>
                        <div class="form-group">
                            <label for="tax">个人所得税</label>
                            <input type="number" id="tax" name="tax" placeholder="请输入个人所得税" step="0.01">
                        </div>
                        <div class="form-group">
                            <label for="description">备注</label>
                            <textarea id="description" name="description" rows="3" placeholder="请输入备注"></textarea>
                        </div>
                        <div class="action-buttons">
                            <button type="submit" class="btn btn-primary">保存</button>
                            <a href="overview.html" class="btn btn-secondary">取消</a>
                        </div>
                    </form>
                </div>
            </main>
        </div>
    </div>

    <script>
        $(document).ready(function() {
            // 检查登录状态
            checkLoginStatus();

            // 显示用户名
            const username = localStorage.getItem('username');
            if (username) {
                $('#username-display').text(username);
            }

            // 退出登录
            /*$('#logout-btn').click(function() {
                localStorage.removeItem('token');
                localStorage.removeItem('username');
                window.location.href = '../../index.html';
            });*/

            // 获取URL参数中的员工ID
            const urlParams = new URLSearchParams(window.location.search);
            const employeeId = urlParams.get('id');

            if (!employeeId) {
                alert('未找到员工ID');
                window.location.href = 'overview.html';
            } else {
                // 加载员工信息和薪酬详情
                loadEmployeeInfo(employeeId);
                loadSalaryDetails(employeeId);
            }

            // 表单提交事件
            $('#salary-form').submit(function(e) {
                e.preventDefault();

                // 表单验证
                if (!validateForm()) {
                    return;
                }

                // 获取表单数据
                const formData = {
                    employeeId: $('#employee-id').val().trim(),
                    effectiveDate: $('#effective-date').val().trim(),
                    baseSalary: parseFloat($('#base-salary').val().trim()),
                    bonus: parseFloat($('#bonus').val().trim() || 0),
                    benefits: parseFloat($('#benefits').val().trim() || 0),
                    insurance: parseFloat($('#insurance').val().trim() || 0),
                    tax: parseFloat($('#tax').val().trim() || 0),
                    description: $('#description').val().trim()
                };

                // 提交表单数据
                window.api.salary.update(formData)
                    .then(response => {
                        if (response) {
                            alert('保存成功');
                            window.location.href = 'overview.html';
                        } else {
                            alert('保存失败');
                        }
                    })
                    .catch(error => {
                        console.error('Failed to update salary:', error);
                        alert('保存失败，请重试');
                    });
            });

            /*function checkLoginStatus() {
                const token = localStorage.getItem('token');
                if (!token) {
                    window.location.href = '../../index.html';
                }
            }*/

            function loadEmployeeInfo(id) {
                // 显示加载状态
                $('.employee-info-card .card-body').html('<div class="loading-spinner"><div class="spinner-border text-primary"></div></div>');

                // 使用模拟数据代替API调用
                setTimeout(() => {
                    const mockEmployee = {
                        id: id,
                        name: '张三',
                        department: '技术部',
                        position: '前端开发工程师',
                        hireDate: '2020-01-15'
                    };

                    // 填充员工信息
                    $('#employee-id').val(mockEmployee.id);
                    $('#employee-name').text(mockEmployee.name);
                    $('#employee-department').text(mockEmployee.department);
                    $('#employee-position').text(mockEmployee.position);
                    $('#employee-hire-date').text(mockEmployee.hireDate);
                }, 800);
            }

            function loadSalaryDetails(id) {
                // 显示加载状态
                $('.salary-form-card .card-body, .summary-card .card-body').html('<div class="loading-spinner"><div class="spinner-border text-primary"></div></div>');

                // 使用模拟数据代替API调用
                setTimeout(() => {
                    // 设置默认生效日期为今天
                    const today = new Date().toISOString().split('T')[0];
                    $('#effective-date').val(today);
                    $('#base-salary').val('15000');
                    $('#bonus').val('3000');
                    $('#benefits').val('2000');
                    $('#insurance').val('1200');
                    $('#tax').val('1500');
                    $('#description').val('季度薪酬调整');

                    // 初始化表单监听器
                    setupFormListeners();
                    // 计算初始薪酬摘要
                    calculateSalarySummary();
                }, 1000);
            }

            function setupFormListeners() {
                // 防止重复绑定事件
                if (window.formListenersSetup) return;
                window.formListenersSetup = true;

                // 为所有薪资输入字段添加事件监听器
                const salaryInputs = $('#base-salary, #bonus, #benefits, #insurance, #tax');
                salaryInputs.on('input', function() {
                    validateForm();
                    calculateSalarySummary();
                });
            }

            function calculateSalarySummary() {
                // 获取表单值并转换为数字
                const baseSalary = parseFloat($('#base-salary').val()) || 0;
                const bonus = parseFloat($('#bonus').val()) || 0;
                const benefits = parseFloat($('#benefits').val()) || 0;
                const insurance = parseFloat($('#insurance').val()) || 0;
                const tax = parseFloat($('#tax').val()) || 0;

                // 计算薪酬摘要
                const grossIncome = baseSalary + bonus + benefits;
                const totalDeductions = insurance + tax;
                const netIncome = grossIncome - totalDeductions;

                // 更新摘要卡片显示
                $('.summary-card .card-body').html(`
                    <div class="summary-row"><span class="summary-label">总收入:</span> <span class="summary-value">¥${grossIncome.toFixed(2)}</span></div>
                    <div class="summary-row"><span class="summary-label">扣除总额:</span> <span class="summary-value">¥${totalDeductions.toFixed(2)}</span></div>
                    <div class="summary-row summary-total"><span class="summary-label">净收入:</span> <span class="summary-value">¥${netIncome.toFixed(2)}</span></div>
                `);
            }

            function validateForm() {
                let isValid = true;

                // 验证生效日期
                const effectiveDate = $('#effective-date').val().trim();
                if (!effectiveDate || !Validator.isDate(effectiveDate)) {
                    alert('请选择有效的生效日期');
                    isValid = false;
                }

                // 验证基本工资
                const baseSalary = $('#base-salary').val().trim();
                if (!baseSalary || !Validator.isMoney(baseSalary) || baseSalary <= 0) {
                    alert('请输入有效的基本工资');
                    isValid = false;
                }

                // 验证奖金
                const bonus = $('#bonus').val().trim();
                if (bonus && !Validator.isMoney(bonus)) {
                    alert('请输入有效的奖金');
                    isValid = false;
                }

                // 验证福利
                const benefits = $('#benefits').val().trim();
                if (benefits && !Validator.isMoney(benefits)) {
                    alert('请输入有效的福利');
                    isValid = false;
                }

                // 验证社保
                const insurance = $('#insurance').val().trim();
                if (insurance && !Validator.isMoney(insurance)) {
                    alert('请输入有效的社保');
                    isValid = false;
                }

                // 验证个人所得税
                const tax = $('#tax').val().trim();
                if (tax && !Validator.isMoney(tax)) {
                    alert('请输入有效的个人所得税');
                    isValid = false;
                }

                return isValid;
            }
        });
    </script>
</body>
</html>